package com.polaris.live.dialog_fragment.room_background.fragment

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentRoomBackgroundBinding
import com.polaris.live.dialog.RoomDiyBackgroundDetailDialog
import com.polaris.live.interface_bag.BackPackDataImpl
import com.polaris.live.interface_bag.BackPackSelectCallback
import com.polaris.live.resp.back_resp.UploadTimesConfig
import com.polaris.live.resp.back_resp.UserBackpackDecorationResp
import com.polaris.live.ui.backpack.fragment.BackpackFragment
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.viewmodel.RoomBackgroundViewModel

/**
 * RoomBackgroundFragment
 *
 * @author Created by 半仙 on 2024/12/18/018 16:16
 */
class RoomBackgroundFragment : BaseVbFragment<RoomBackgroundViewModel, FragmentRoomBackgroundBinding>(),
    BackPackDataImpl, BackPackSelectCallback {

    private val mAnchorId by lazy { arguments?.getLong("anchorId") }

    //是否为半弹窗
    private val mIsPopup by lazy { arguments?.getBoolean("isPopup", true) ?: true }

    private val mFragments = mutableListOf<Fragment>()

    private var mUploadTimesConfig: UploadTimesConfig? = null

    private var mRouteIndex = EFFICIENT

    private val mBackpackFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.PARTY_BACKGROUND,
                "isPopup" to mIsPopup
            )
            setOnBackPackSelectCallback(this@RoomBackgroundFragment)
            setOnSelectCallback(object : OnBackgroundSelectCallback {
                override fun setOnSelectCallback(index: Int, needUnmount: Boolean) {
                    setUncheck(index, needUnmount)
                }
            })
        }
    }

    private val roomBackgroundDiyFragment by lazy {
        RoomBackgroundDiyFragment().apply {
            arguments = bundleOf("anchorId" to mAnchorId, "isPopup" to mIsPopup)
            setOnClickPreviewListener { background ->
                mOnBackPackSelectCallback?.onBackPackSelectCallback(
                    UserBackpackDecorationResp(
                        backpackId = background.position.toLong(),
                        decorationId = background.position.toLong(),
                        decorationType = CommonConst.DressUp.PARTY_BACKGROUND,
                        displayUrl = background.background.toString(),
                        effectDisplayUrl = background.background,
                        name = "",
                        received = false,
                        useStatus = background.useStatus
                    )
                )
            }
            setOnSelectCallback(object : OnBackgroundSelectCallback {
                override fun setOnSelectCallback(index: Int, needUnmount: Boolean) {
                    setUncheck(index, needUnmount)
                }
            })
        }
    }

    private fun setUncheck(index: Int, needUnmount: Boolean) {
        when (index) {
            0 -> mBackpackFragment.setUncheckItem(needUnmount)
            2 -> roomBackgroundDiyFragment.setUncheckItem(needUnmount)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        mFragments.add(mBackpackFragment)

        if (mIsPopup) {
            //半弹窗展示购买背景
            mFragments.add(RoomBackgroundShoppingFragment().apply {
                setOnBuyShowCallback {
                    setBackground(EFFICIENT)
                    this@RoomBackgroundFragment.mBinding.vp.currentItem = 0
                }
                setOnBuySuccessCallback {
                    mBackpackFragment.updateData(CommonConst.DressUp.PARTY_BACKGROUND)
                }
            })
            //获取有效背景和自定义背景槽位
            mViewModel.getDiyAndBackpack()
        } else {
            //背包页隐藏购买背景页
            mBinding.ivWhat.visibility = View.VISIBLE
            mBinding.shoppingTv.visibility = View.GONE
            mViewModel.getBackgroundDiy()
        }


        mFragments.add(roomBackgroundDiyFragment)

        mBinding.vp.adapter = ViewPagerAdapter(mFragments, this)
        mBinding.vp.offscreenPageLimit = mFragments.size
        mBinding.vp.isUserInputEnabled = false

        setBackground(mRouteIndex)
        initListener()
        initObserver()
    }

    private fun initListener() {
        mBinding.effectiveTv.setOnSingleClickListener {
            setBackground(EFFICIENT)
        }
        mBinding.shoppingTv.setOnSingleClickListener {
            setBackground(SHOPPING)
        }
        mBinding.tvCustom.setOnSingleClickListener {
            setBackground(DIY)
        }
        mBinding.ivWhat.setOnSingleClickListener {
            mUploadTimesConfig?.let { it1 -> RoomDiyBackgroundDetailDialog.show(requireContext(), it1) }
        }
    }

    private fun initObserver() {
        mViewModel.mDiyAndBackLiveData.observe(this) { resp ->
            val diyResp = resp.first
            val backpackResp = resp.second
            val item = diyResp?.list?.find { it.useStatus.toBoolean() }
            //判断自定义背景是否有使用的，如果没有则有效背景来处理默认选中的问题
            if (item == null) {
                mBackpackFragment.setonBackPackData(backpackResp ?: emptyList())
            } else {
                mBackpackFragment.setonBackPackData(backpackResp ?: emptyList(), false)
            }
        }
        mViewModel.mDiyBackgroundLiveData.observe(this) { resultState ->
            parseState(resultState, { resp ->
                mUploadTimesConfig = resp.uploadTimesConfig
            })
        }
    }

    private fun setBackground(index: Int) {
        mBinding.effectiveTv.isSelected = false
        mBinding.shoppingTv.isSelected = false
        mBinding.tvCustom.isSelected = false
        when (index) {
            EFFICIENT -> mBinding.effectiveTv.isSelected = true
            SHOPPING -> mBinding.shoppingTv.isSelected = true
            DIY -> mBinding.tvCustom.isSelected = true
        }

        mBinding.vp.currentItem = when (index) {
            DIY -> if (mIsPopup) 2 else 1
            SHOPPING -> if (mIsPopup) 1 else mBinding.vp.currentItem
            else -> index
        }
    }

    private var mOnBackPackSelectCallback: BackPackSelectCallback? = null

    fun setOnBackPackSelectCallback(l: BackPackSelectCallback) {
        mOnBackPackSelectCallback = l
    }

    //背景类型的时候  给背包页数据，判断自定义背景是否有选中的 如果没有则给默认背景选中
    fun setonBackPackData(backPackList: List<UserBackpackDecorationResp>, isDefault: Boolean = true) {
        mBackpackFragment.setonBackPackData(backPackList, isDefault)
    }

    override fun onBackPackDataCallback(backPackList: List<UserBackpackDecorationResp>) {
        mBackpackFragment.onBackPackDataCallback(backPackList)
    }

    override fun onBackPackSelectCallback(position: Int) {
        mBackpackFragment.onBackPackSelectCallback(position)
    }

    override fun onBackPackSelectCallback(item: UserBackpackDecorationResp?) {
        mOnBackPackSelectCallback?.onBackPackSelectCallback(item)
    }

    override fun goShopping(type: Long) {
        mOnBackPackSelectCallback?.goShopping(type)
    }

    fun getType() = CommonConst.DressUp.PARTY_BACKGROUND

    fun tabChange(type: Int?) {
        if (isCreated() && type != null) {
            // 更新 currentItem
            setBackground(type)
        } else {
            type?.let { mRouteIndex = type }
        }
    }

    companion object {

        const val EFFICIENT = 0               //有效背景
        const val DIY = 1                     //自定义背景
        const val SHOPPING = 2                //商城
    }
}

interface OnBackgroundSelectCallback {

    //index是page的下标
    //needUnmount  在自定义背景页的时候给true 表示要吧当前使用的卸掉  因为选中默认就是吧使用中的背景卸掉
    //             在有效背景页的时候就给true 表示要选中默认背景
    fun setOnSelectCallback(index: Int, needUnmount: Boolean = false)
}